package com.unionfetch.content_home.ui.step

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.flexbox.FlexboxLayout
import com.unionfetch.content_home.R
import com.unionftech.common.R.string
import com.unionfetch.content_home.bean.request.SecondStepRequest
import com.unionfetch.content_home.contract.OpenAccountContract
import com.unionfetch.content_home.presenter.OpenAccountPresenter
import com.unionfetch.content_home.ui.dialog.CustomTipDialog
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.bean.SystemUserInfo
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.router.RouterPath
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.Utils

class SecondStepOpenAccountActivity : BaseMvpActivity(), OpenAccountContract.ISecondStepView,
    IUpdate {
    private val mBtnNext by lazy { findViewById<Button>(R.id.btn_next) }
    private val mTvSourceIncome2Error by lazy { findViewById<TextView>(R.id.tv_source_income2_error) }
    private val mTvBenefit2 by lazy { findViewById<TextView>(R.id.tv_benefit2) }
    private val mTvInvestmentIncome2 by lazy { findViewById<TextView>(R.id.tv_investment_income2) }
    private val mTvSavings2 by lazy { findViewById<TextView>(R.id.tv_savings2) }
    private val mTvWages2 by lazy { findViewById<TextView>(R.id.tv_wages2) }
    private val mFblSourceIncome2 by lazy { findViewById<FlexboxLayout>(R.id.fbl_source_income2) }
    private val mTvSourceIncome2Title by lazy { findViewById<TextView>(R.id.tv_source_income2_title) }
    private val mLlSourceIncome2Container by lazy { findViewById<LinearLayout>(R.id.ll_source_income2_container) }
    private val mTvPlanFoundError by lazy { findViewById<TextView>(R.id.tv_plan_found_error) }
    private val mTvPlanFoundNo by lazy { findViewById<TextView>(R.id.tv_plan_found_no) }
    private val mTvPlanFoundYes by lazy { findViewById<TextView>(R.id.tv_plan_found_yes) }
    private val mFblPlanFound by lazy { findViewById<FlexboxLayout>(R.id.fbl_plan_found) }
    private val mTvPlanFundTitle by lazy { findViewById<TextView>(R.id.tv_plan_fund_title) }
    private val mLlPlanFundContainer by lazy { findViewById<LinearLayout>(R.id.ll_plan_fund_container) }
    private val mTvApplicabilityError by lazy { findViewById<TextView>(R.id.tv_applicability_error) }
    private val mTvApplicabilityNo by lazy { findViewById<TextView>(R.id.tv_applicability_no) }
    private val mTvApplicabilityYes by lazy { findViewById<TextView>(R.id.tv_applicability_yes) }
    private val mFblApplicabilityConfirm by lazy { findViewById<FlexboxLayout>(R.id.fbl_applicability_confirm) }
    private val mTvApplicabilityConfirmTitle by lazy { findViewById<TextView>(R.id.tv_applicability_confirm_title) }
    private val mLlApplicabilityContainer by lazy { findViewById<LinearLayout>(R.id.ll_applicability_container) }
    private val mTvApplicabilityTips by lazy { findViewById<TextView>(R.id.tv_applicability_tips) }
    private val mTvApplicabilityEvaluationTitle by lazy { findViewById<TextView>(R.id.tv_applicability_evaluation_title) }
    private val mLlApplicabilityEvaluationContainer by lazy { findViewById<LinearLayout>(R.id.ll_applicability_evaluation_container) }
    private val mTvExperienceError by lazy { findViewById<TextView>(R.id.tv_experience_error) }
    private val mTvMoreFiveYear by lazy { findViewById<TextView>(R.id.tv_more_five_year) }
    private val mTvTwoFiveYear by lazy { findViewById<TextView>(R.id.tv_two_five_year) }
    private val mTvLessOneYear by lazy { findViewById<TextView>(R.id.tv_less_one_year) }
    private val mTvWithoutExperience by lazy { findViewById<TextView>(R.id.tv_without_experience) }
    private val mFblYourExperience by lazy { findViewById<FlexboxLayout>(R.id.fbl_your_experience) }
    private val mTvExperienceTitle by lazy { findViewById<TextView>(R.id.tv_experience_title) }
    private val mLlExperienceContainer by lazy { findViewById<LinearLayout>(R.id.ll_experience_container) }
    private val mTvIsUsaError by lazy { findViewById<TextView>(R.id.tv_is_usa_error) }
    private val mTvNoUsa by lazy { findViewById<TextView>(R.id.tv_no_usa) }
    private val mTvIsUsa by lazy { findViewById<TextView>(R.id.tv_is_usa) }
    private val mFblUsaPerson by lazy { findViewById<FlexboxLayout>(R.id.fbl_usa_person) }
    private val mTvUsaPersonTitle by lazy { findViewById<TextView>(R.id.tv_usa_person_title) }
    private val mLlUsaPersonContainer by lazy { findViewById<LinearLayout>(R.id.ll_usa_person_container) }
    private val mTvSourceIncomeError by lazy { findViewById<TextView>(R.id.tv_source_income_error) }
    private val mTvBenefit by lazy { findViewById<TextView>(R.id.tv_benefit) }
    private val mTvInvestmentIncome by lazy { findViewById<TextView>(R.id.tv_investment_income) }
    private val mTvSavings by lazy { findViewById<TextView>(R.id.tv_savings) }
    private val mTvWages by lazy { findViewById<TextView>(R.id.tv_wages) }
    private val mFblSourceIncome by lazy { findViewById<FlexboxLayout>(R.id.fbl_source_income) }
    private val mTvSourceIncomeTitle by lazy { findViewById<TextView>(R.id.tv_source_income_title) }
    private val mLlSourceIncomeContainer by lazy { findViewById<LinearLayout>(R.id.ll_source_income_container) }
    private val mTvAssetAppraisalTitle by lazy { findViewById<TextView>(R.id.tv_asset_appraisal_title) }

    private val mIvBack by lazy { findViewById<ImageView>(R.id.iv_step_back) }
    private val mIvStep by lazy { findViewById<ImageView>(R.id.iv_step) }
    private val mIvCustomer by lazy { findViewById<ImageView>(R.id.iv_customer) }
    private lateinit var mContainerSelectMap: MutableMap<ViewGroup, Int>
    private var mIsIb = false

    @InjectPresenter
    private lateinit var mOpenPresenter: OpenAccountPresenter

    companion object {
        private const val PRAMS_IS_IB = "params_is_ib"

        @JvmStatic
        fun startThis(context: Context, isIb: Boolean = false) {
            Intent(context, SecondStepOpenAccountActivity::class.java).apply {
                if (context !is Activity) {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                putExtra(PRAMS_IS_IB, isIb)
                context.startActivity(this)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun initLayout() = R.layout.activity_second_step_open_account

    override fun obtainIntentData(intent: Intent) {
        super.obtainIntentData(intent)
        mIsIb = intent.getBooleanExtra(PRAMS_IS_IB, false)
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvAssetAppraisalTitle.text =
            DynamicResourceManager.getString(mContext, string.asset_appraisal)
        mTvSourceIncomeTitle.text =
            DynamicResourceManager.getString(mContext, string.your_source_income)
        mTvWages.text = DynamicResourceManager.getString(mContext, string.wages)
        mTvSavings.text = DynamicResourceManager.getString(mContext, string.savings)
        mTvInvestmentIncome.text =
            DynamicResourceManager.getString(mContext, string.investment_income)
        mTvBenefit.text = DynamicResourceManager.getString(mContext, string.benefit)
        mTvUsaPersonTitle.text =
            DynamicResourceManager.getString(mContext, string.you_is_usa_person)
        mTvIsUsa.text = DynamicResourceManager.getString(mContext, string.yes)
        mTvNoUsa.text = DynamicResourceManager.getString(mContext, string.no)
        mTvExperienceTitle.text =
            DynamicResourceManager.getString(mContext, string.your_experience)
        mTvWithoutExperience.text =
            DynamicResourceManager.getString(mContext, string.without_experience)
        mTvLessOneYear.text = DynamicResourceManager.getString(mContext, string.less_one_year)
        mTvTwoFiveYear.text = DynamicResourceManager.getString(mContext, string.two_five_year)
        mTvMoreFiveYear.text = DynamicResourceManager.getString(mContext, string.more_five_year)

        mTvApplicabilityEvaluationTitle.text =
            DynamicResourceManager.getString(mContext, string.applicability_evaluation)
        mTvApplicabilityTips.text =
            DynamicResourceManager.getString(mContext, string.applicability_tips)
        mTvApplicabilityConfirmTitle.text =
            DynamicResourceManager.getString(mContext, string.applicability_confirm)
        mTvApplicabilityYes.text = DynamicResourceManager.getString(mContext, string.yes)
        mTvApplicabilityNo.text = DynamicResourceManager.getString(mContext, string.no)
        mTvPlanFundTitle.text =
            DynamicResourceManager.getString(mContext, string.you_plan_found_can_bear)
        mTvPlanFoundYes.text = DynamicResourceManager.getString(mContext, string.yes)
        mTvPlanFoundNo.text = DynamicResourceManager.getString(mContext, string.no)
        mTvSourceIncome2Title.text =
            DynamicResourceManager.getString(mContext, string.your_source_income)
        mTvWages2.text = DynamicResourceManager.getString(mContext, string.wages)
        mTvSavings2.text = DynamicResourceManager.getString(mContext, string.savings)
        mTvInvestmentIncome2.text =
            DynamicResourceManager.getString(mContext, string.investment_income)
        mTvBenefit2.text = DynamicResourceManager.getString(mContext, string.benefit)
        mBtnNext.text = DynamicResourceManager.getString(string.next_step)
    }

    override fun setListener() {
        super.setListener()
        mIvBack.setOnClickListener(this)
        mIvCustomer.setOnClickListener(this)
        setContainerChildListener(mFblSourceIncome)
        setContainerChildListener(mFblUsaPerson)
        setContainerChildListener(mFblYourExperience)
        setContainerChildListener(mFblApplicabilityConfirm)
        setContainerChildListener(mFblPlanFound)
        setContainerChildListener(mFblSourceIncome2)
        mBtnNext.setOnClickListener(this)
    }

    override fun setView() {
        super.setView()
        hideTitleBar()
        initTitleBar()
        mBtnNext.isEnabled = false
        initSelectMap()
    }

    private fun initSelectMap() {
        mContainerSelectMap = HashMap()
        mContainerSelectMap[mFblSourceIncome] = -1
        mContainerSelectMap[mFblUsaPerson] = -1
        mContainerSelectMap[mFblYourExperience] = -1
    }

    private fun initTitleBar() {
        if (mIsIb) {
            mIvStep.setImageResource(R.drawable.ic_ib_step_1)
        } else {
            mIvStep.setImageResource(R.drawable.ic_step_2)
        }
    }

    private fun setContainerChildListener(layout: FlexboxLayout) {
        for (index in 0 until layout.childCount) {
            layout.getChildAt(index)?.also { childView ->
                childView.setOnClickListener {
                    if (!Utils.isFastDoubleClick(childView.id)) {
                        //不允许选中之后，取消选中
                        if (!childView.isSelected) {
                            doClick(childView)
                            childView.isSelected = !childView.isSelected
                            removeOtherSelect(childView, layout)
                            mContainerSelectMap[layout] = index
                            checkButtonEnable()
                        }
                    }
                }
            }
        }
    }

    private fun checkButtonEnable() {
        if (!mContainerSelectMap.containsValue(-1)) {
            mBtnNext.isEnabled = true
        } else {
            mBtnNext.isEnabled = false
        }
    }

    private fun removeOtherSelect(jumpView: View, layout: FlexboxLayout) {
        for (i in 0 until layout.childCount) {
            layout.getChildAt(i)?.also { childView ->
                if (childView.id != jumpView.id) {
                    childView.isSelected = false
                }
            }
        }
    }

    /**
     * 屏蔽物理返回键
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.iv_step_back -> {
                showLeaveDialog()
            }

            R.id.iv_customer -> {
                ToastUtils.longToast(
                    DynamicResourceManager.getString(
                        mContext, string.developing
                    )
                )
            }

            R.id.tv_benefit -> {
                if (!mLlApplicabilityEvaluationContainer.isShown) {
                    mLlApplicabilityEvaluationContainer.visibility = View.VISIBLE
                    mContainerSelectMap[mFblApplicabilityConfirm] = -1
                    mContainerSelectMap[mFblPlanFound] = -1
                    mContainerSelectMap[mFblSourceIncome2] = -1
                }
            }

            R.id.tv_wages, R.id.tv_savings, R.id.tv_investment_income -> {
                if (mLlApplicabilityEvaluationContainer.isShown) {
                    mLlApplicabilityEvaluationContainer.visibility = View.GONE
                    removeApplicabilitySelect()

                }
            }

            R.id.btn_next -> {
                submit()
            }
        }
    }

    private fun removeApplicabilitySelect() {
        var index = mContainerSelectMap[mFblApplicabilityConfirm] ?: -1
        if (index != -1) {
            mFblApplicabilityConfirm.getChildAt(index)?.isSelected = false
        }
        index = mContainerSelectMap[mFblPlanFound] ?: -1
        if (index != -1) {
            mFblPlanFound.getChildAt(index)?.isSelected = false
        }
        index = mContainerSelectMap[mFblSourceIncome2] ?: -1
        if (index != -1) {
            mFblSourceIncome2.getChildAt(index)?.isSelected = false
        }
        mContainerSelectMap.remove(mFblApplicabilityConfirm)
        mContainerSelectMap.remove(mFblPlanFound)
        mContainerSelectMap.remove(mFblSourceIncome2)
    }

    private fun submit() {
        getRequestBean()?.also { request ->
            if (mIsIb) {
                ThirdStepOpenAccountActivity.startThis(mContext, request)
                finish()
            } else {
                val userToken = GlobalInfoManager.getInstance().getUserToken()
                mOpenPresenter.submitSecondStep(userToken, request)
            }
        }
    }

    private fun getRequestBean(): SecondStepRequest? {
        val request = SecondStepRequest()
        for (entry in mContainerSelectMap) {
            val container = entry.key
            val selectIndex = entry.value
            if (selectIndex == -1) {
                return null
            }
            container.getChildAt(selectIndex)?.also { view ->
                LogUtils.d("getRequestBean  view->${view}  tag-->${view.tag}")
                when (container) {
                    //财富来源
                    mFblSourceIncome -> request.sourceOfFunds = view.tag.toString().toInt()
                    mFblUsaPerson -> request.usPayTax = view.tag.toString()
                    mFblYourExperience -> request.tradingExperience = view.tag.toString().toInt()
                    mFblApplicabilityConfirm -> request.agreeRisk = view.tag.toString().toInt()
                    mFblPlanFound -> request.sustainLosses = view.tag.toString().toInt()
                    mFblSourceIncome2 -> request.sourceOfFunds = view.tag.toString().toInt()
                }
            }
        }
        return request
    }

    private fun showLeaveDialog() {
        val dialog = CustomTipDialog(mContext)
        dialog.setTopRes(R.drawable.ic_circle_warning)
            .setTitle(DynamicResourceManager.getString(mContext, string.confirm_leave))
            .setCancelText(
                DynamicResourceManager.getString(
                    mContext, string.cancel
                )
            ).setConfirmText(
                DynamicResourceManager.getString(
                    mContext, string.confirm
                )
            ).setCallBack { confirm ->
                if (confirm) {
                    gotoMain()
                }
                dialog.dismiss()
            }.show()
    }

    private fun gotoMain() {
        ARouter.getInstance().build(RouterPath.UFUFMainStandardActivityInfo.PATH).navigation()
        finish()
    }

    override fun handleSecondStep(response: ResponseResult<Any?>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            //更新SystemUserInfo
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_USR_INFO)
            GlobalInfoManager.getInstance().addListener(this)
        } else {
            LogUtils.d(
                SecondStepOpenAccountActivity::class.java.simpleName,
                "handleSecondStep error->$response"
            )
            response.toast()
        }
    }

    override fun onUpdate(obj: Any?) {
        if (obj is SystemUserInfo) {
            GlobalInfoManager.getInstance().remove(this)
            ThirdStepOpenAccountActivity.startThis(mContext)
            finish()
        }
    }
}